package com.arpa.wms.controller;

import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.map.MapUtil;
import com.arpa.core.web.MediaTypes;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.wms.domain.consts.CommonConst;
import com.arpa.wms.domain.consts.PropertyConst;
import com.arpa.wms.domain.dto.BatchRuleDTO;
import com.arpa.wms.domain.dto.BatchRuleFormDTO;
import com.arpa.wms.domain.entity.BatchRule;
import com.arpa.wms.domain.enums.StatusEnum;
import com.arpa.wms.domain.vo.BatchRuleVO;
import com.arpa.wms.service.IBatchRuleService;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 批次规则 Controller
 * </p>
 *
 * @author LEO
 * @since 2020-08-11
 */
@Api(tags = "批次规则")
@RestController
@RequestMapping(value="/batchRule", produces = "application/json;charset=UTF-8")
@Log4j2
public class BatchRuleController  {

   @Autowired
   private IBatchRuleService iBatchRuleService;


    /**
     * 前端打印异常数据接口
     * @param response
     * @return
     */
    @ApiOperation(value = "打印异常信息", notes = "打印异常信息")
    @GetMapping("/dayin")
    public Result jspalAuthentication(String dayin, HttpServletResponse response){
        log.info(dayin);
        System.out.println(dayin);
        return Result.ok().data(dayin);
    }

    /**
     * 获取 批次规则 列表
     *
     * @param batchRuleDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 批次规则 列表", notes = "获取 批次规则 列表")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = BatchRuleVO.class))
    @NeedLogin
    @GetMapping()
    public Result list(BatchRuleDTO batchRuleDTO, HttpServletRequest request) {
        try {
            List<String> shipmentCodes = UserUtil.getAuthorizeShipmentCodes();
            if (IterUtil.isEmpty(shipmentCodes)) {
                throw new ServiceException(CommonConst.PLEASE_AUTHORIZE_THE_WAREHOUSE_AND_SHIPMENT_FIRST_AND_THEN_LOG_IN_AGAIN);
            }
            //登录仓库授权的货主过滤
            batchRuleDTO.setShipmentCodes(shipmentCodes);
            //所属机构的过滤
            batchRuleDTO.setGroupCode(UserUtil.getBranchCode());
            BatchRuleVO batchRuleVosum = iBatchRuleService.queryListSum(batchRuleDTO);
            List<BatchRuleVO> batchRuleVOList = iBatchRuleService.queryList(batchRuleDTO);

            Page returnPage = new Page(batchRuleDTO.getPageNum(),batchRuleDTO.getPageSize());
            returnPage.setRecords(batchRuleVOList);
            returnPage.setTotal(batchRuleVosum.getTotal());
            returnPage.setSumObject(batchRuleVosum);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 添加 批次规则
     *
     * @param entity BatchRule
     * @param request
     * @return
     */
    @ApiOperation(value = "添加 批次规则 ", notes = "添加 批次规则 ")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PostMapping()
    public Result create(@Validated(BatchRule.Save.class) BatchRule entity, HttpServletRequest request) {
        try {
            entity.setGroupCode(UserUtil.getBranchCode());
            iBatchRuleService.save(entity);
            return Result.ok("添加成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
    * 获取批次规则详情
    *
    * @param code
    * @param request
    * @return
    */
    @ApiOperation(value = "获取批次规则详情", notes = "获取批次规则详情")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
        @ApiImplicitParam(name = "code", value = "批次规则code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = BatchRule.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result batchRule(@PathVariable String code, HttpServletRequest request) {
        try {
            BatchRuleVO batchRuleVO = iBatchRuleService.getByCode(code);
            batchRuleVO.setGroupCode(UserUtil.getBranchCode());
            return Result.ok().data(batchRuleVO);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 修改批次规则
     *
     * @param entity 批次规则
     * @param request
     * @return
     */
    @ApiOperation(value = "修改批次规则", notes = "修改批次规则")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping()
    public Result update(@Validated(BatchRuleFormDTO.Update.class) BatchRuleFormDTO entity, HttpServletRequest request) {
        if(StringUtils.isBlank(entity.getCode())){
            return Result.error("code不能为空");
        }
        int updateNum = iBatchRuleService.updateByCode(entity);
        if(updateNum == 0){
            return Result.error("没有更新数据！code:"+entity.getCode());
        }else{
            return Result.ok("修改成功,更新"+updateNum+"条数据！");
        }
    }



    /**
     * 启用批次
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "启用批次", notes = "启用批次")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping("/active")
    public Result active(@RequestParam List<String> codes, HttpServletRequest request) {
        Map<String, Object> result = iBatchRuleService.activeStatus(codes, StatusEnum.ACTIVE);
        Integer success = MapUtil.getInt(result, PropertyConst.SUCCESS);
        int failNum = codes.size() - success;
        return Result.ok("启用成功" + success + "条；失败" + failNum + "条；");
    }

    /**
     * 停用
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "停用批次", notes = "停用批次")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping("/unactive")
    public Result unactive(@RequestParam List<String> codes, HttpServletRequest request) {

        Map<String, Object> result = iBatchRuleService.activeStatus(codes, StatusEnum.UNACTIVE);
        List<String> msg = MapUtil.get(result,"msg",List.class);
        String message = "";
        if(IterUtil.isNotEmpty(msg)){
            for(String m: msg){
                message+="<br><font color='red'>批次规则【"+m+"】停用失败，正在使用中;</font>";
            }
        }
        Integer success = MapUtil.getInt(result, PropertyConst.SUCCESS);
        int failNum = codes.size() - success;
        return Result.ok("停用成功" + (MapUtil.getInt(result,PropertyConst.SUCCESS) == null ? 0 : MapUtil.getInt(result,PropertyConst.SUCCESS))  + "条；失败" + (MapUtil.getInt(result,"fail") == null ? failNum : MapUtil.getInt(result,"fail")) + "条；"+message);
    }



    @ApiOperation(value = "删除批次信息", notes = "删除批次信息", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "codes", value = "单位code", paramType = "path", dataType = "String")
    })
    @NeedLogin
    @DeleteMapping(value = "")
    public Result delete(@RequestParam List<String> codes, HttpServletRequest request) {
        try {
            Map<String, Object> result = iBatchRuleService.removeByCode(codes);
            Integer success = MapUtil.getInt(result, PropertyConst.SUCCESS);
            List<String> notDelete = MapUtil.get(result, "notDelete", List.class);
            int failNum = codes.size() - success;
            StringBuilder builder = new StringBuilder();
            builder.append("删除成功" + success + "条；失败" + failNum + "条；");
            if(IterUtil.isNotEmpty(notDelete)){
                for (String m:notDelete) {
                    builder.append("<br><font color='red'>批次规则【"+m+"】删除失败，已被启用过;</font>");
                }
            }
            return Result.ok(builder.toString());
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }



    @ApiOperation(value = "获取货主批次列表", notes = "获取货主批次列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @GetMapping(value = "/findByShipmentCode")
    public Result findByShipmentCode(String shipmentCode, HttpServletRequest request) {
        try {
            List<Map<String, Object>> brands = iBatchRuleService.findByShipmentCode(shipmentCode);
            return Result.ok().data(brands);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

}
